<template>
  <div class="teacher-calling">
    <!-- 发起点名卡片 -->
    <el-card class="calling-card">
      <template #header>
        <div class="card-header">
          <span>发起点名</span>
        </div>
      </template>

      <el-form :model="form" label-width="120px">
        <el-form-item label="选择班级">
          <el-select
              v-model="form.classId"
              placeholder="请选择班级"
              @change="checkActiveCall">
            <el-option
                v-for="item in classList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              @click="startCalling"
              :loading="loading"
              :disabled="hasActiveCalling">
            发起点名
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 进行中的点名记录 -->
    <el-card v-if="hasActiveCalling" class="calling-record">
      <template #header>
        <div class="card-header">
          <span>当前进行中的点名</span>
          <el-tag type="success">
            已签到: {{ getSignedCount() }}/{{ callingDetails.length }}
          </el-tag>
          <el-tag type="warning" v-if="activeCall">
            剩余时间: {{ getRemainingTime() }}
          </el-tag>
        </div>
      </template>

      <el-table :data="callingDetails" style="width: 100%">
        <el-table-column prop="studentName" label="学生姓名"/>
        <el-table-column label="签到状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.answerResult)">
              {{ getStatusText(scope.row.answerResult) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="answerTime" label="签到时间">
          <template #default="scope">
            {{ scope.row.answerTime ? formatDateTime(scope.row.answerTime) : '-' }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { formatDateTime } from '@/utils/datetime'
import { mapGetters } from 'vuex'  // 引入 mapGetters

export default {
  name: "Attendance",
  data() {
    return {
      form: {
        classId: null
      },
      loading: false,
      classList: [],
      callingDetails: [],
      activeCall: null,
      hasActiveCalling: false,
      timer: null,
      // 添加分页参数
      pageParams: {
        currentPage: 1,
        pageSize: 100  // 设置较大的数值以获取所有班级
      }
    }
  },
  computed: {
    ...mapGetters(['getUser'])
  },
  created() {
    this.getClassList().then(() => {
      if (this.form.classId) {
        this.checkActiveCall(this.form.classId)
      }
    })
  },
  beforeUnmount() {
    this.clearTimer()
  },
  methods: {
    // 检查是否有进行中的点名
    // 修改 checkActiveCall 方法
    async checkActiveCall(classId) {
      if (!classId) return

      try {
        const res = await this.$axios.get('/teaching-calling/active', {
          params: { classId }
        })
        console.log('Active call check response:', res.data)

        if (res.data.code === 200 && res.data.data) {
          const { calling, details } = res.data.data  // 解构获取数据
          this.activeCall = calling
          this.callingDetails = details  // 直接使用返回的详情
          this.hasActiveCalling = true
          this.startRefreshTimer(calling.id)

          ElMessage.warning(`班级 ${this.getClassName(classId)} 有进行中的点名`)
        } else {
          this.activeCall = null
          this.hasActiveCalling = false
          this.callingDetails = []
          this.clearTimer()
        }
      } catch (error) {
        console.error('检查进行中点名失败:', error)
      }
    },

// 添加获取班级名称的方法
    getClassName(classId) {
      const classItem = this.classList.find(item => item.id === classId)
      return classItem ? classItem.name : '未知班级'
    },

      // 获取剩余时间
    getRemainingTime() {
      if (!this.activeCall) return ''

      const endTime = new Date(this.activeCall.endTime).getTime()
      const now = new Date().getTime()
      const diff = endTime - now

      if (diff <= 0) return '已结束'

      const minutes = Math.floor(diff / 60000)
      const seconds = Math.floor((diff % 60000) / 1000)
      return `${minutes}分${seconds}秒`
    },

    // 清除定时器
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    // 获取教师负责的班级列表
    // 获取教师负责的班级列表
    async getClassList() {
      try {
        const teacherId = this.getUser.id
        console.log('Teacher ID:', teacherId)

        const res = await this.$axios.get('/manager-class/teacher-classes', {
          params: {
            teacherId: teacherId,
            currentPage: this.pageParams.currentPage,
            pageSize: this.pageParams.pageSize
          }
        })

        if (res.data.code === 200) {
          this.classList = res.data.data.records
          console.log('Class List:', this.classList)

          // 如果有选中的班级，立即检查点名状态
          if (this.form.classId) {
            await this.checkActiveCall(this.form.classId)
          }
        } else {
          ElMessage.error(res.data.msg || '获取班级列表失败')
        }
      } catch (error) {
        console.error('获取班级列表失败:', error)
        ElMessage.error('获取班级列表失败')
      }
    },

    // 发起点名
    // 修改开始点名方法
    async startCalling() {
      if (!this.form.classId) {
        ElMessage.warning('请选择班级')
        return
      }

      if (this.hasActiveCalling) {
        ElMessage.warning('该班级已有进行中的点名')
        return
      }

      this.loading = true
      try {
        const teacherId = this.getUser.id
        const res = await this.$axios.post('/teaching-calling/teacher/start', {
          classId: this.form.classId,
          teacherId: teacherId
        })

        if (res.data.code === 200) {
          ElMessage.success('点名发起成功')
          this.activeCall = res.data.data
          this.hasActiveCalling = true
          await this.getCallingDetails(res.data.data.id)  // 确保传递正确的 ID
          this.startRefreshTimer(res.data.data.id)
        }
      } catch (error) {
        console.error('发起点名失败:', error)
        ElMessage.error(error.response?.data?.msg || '发起点名失败')
      } finally {
        this.loading = false
      }
    },

    // 获取点名详情
// 获取点名详情
    async getCallingDetails(callId) {
      if (!callId) {
        console.error('缺少 callId 参数')
        return
      }

      try {
        console.log('Getting details for callId:', callId) // 调试用
        const res = await this.$axios.get('/teaching-calling/details', {
          params: { callId: callId }  // 确保传递 callId
        })
        if (res.data.code === 200) {
          this.callingDetails = res.data.data
          console.log('Call details:', this.callingDetails) // 调试用
        }
      } catch (error) {
        console.error('获取点名详情失败:', error)
        ElMessage.error('获取点名详情失败')
      }
    },

    // 开始定时刷新
    startRefreshTimer(callId) {
      if (this.timer) clearInterval(this.timer)
      this.timer = setInterval(() => {
        this.getCallingDetails(callId)
      }, 5000)
    },

    // 获取已签到人数
    getSignedCount() {
      return this.callingDetails.filter(item => item.answerResult === '1').length
    },

    // 获取状态标签类型
    getStatusType(status) {
      const types = {
        '0': 'info',
        '1': 'success',
        '2': 'warning',
        '3': 'danger'
      }
      return types[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const texts = {
        '0': '未签到',
        '1': '已签到',
        '2': '迟到',
        '3': '请假'
      }
      return texts[status] || '未知'
    },

    formatDateTime
  }
}
</script>

<style scoped>
.teacher-calling {
  padding: 20px;
}

.calling-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-tag {
  margin-left: 10px;
}
</style>